package com.sgb.kjwl.view.ui.fragment.home;

import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.tabs.TabLayout;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.auction.adapter.AuctionHallAdapter;
import com.sgb.auction.entity.AuctionListEntity;
import com.sgb.kjwl.BaseHeightViewPagerFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentCommodityMaterialBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.entity.BannerEntity;
import com.sgb.kjwl.model.entity.DemandHallListEntity;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.model.entity.SearchMaterialEntity3;
import com.sgb.kjwl.model.entity.request.MaterialFilterJson;
import com.sgb.kjwl.model.entity.supplier3.SupplierRecommendEntity;
import com.sgb.jicai.entity.FactoryCentralizedItemEntity;
import com.sgb.kjwl.view.event.CategoryEvent2;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.activity.manage.ShopInfoForCompanyTradesActivity;
import com.sgb.kjwl.view.ui.activity.material.ConcreteDetailActivity2;
import com.sgb.kjwl.view.ui.activity.self.shop.ShopGoodsDetailActivity;
import com.sgb.kjwl.view.ui.adapter.carrierDemand.DemandHallAdapter;
import com.sgb.kjwl.view.ui.adapter.home.FactoryCentralizedListItemAdapter;
import com.sgb.kjwl.view.ui.adapter.home.MaterialHomeAdapter;
import com.sgb.kjwl.view.ui.adapter.home.MaterialHomeAdapter1;
import com.sgb.kjwl.view.ui.adapter.supplier3.SupplierRecommendAdapter;
import com.sgb.kjwl.view.widget.HomeGoodsSelectionTypePopWindow;
import com.sgb.kjwl.viewmodel.home.CommodityMaterialModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.util.ClickUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

/**
 * author: 005
 * createDate: 2021/2/5 10:14
 * copyright (C), 2021-2021, 中均科技有限公司
 * fileName: CommodityMaterialFragment
 * description: 商品材料的复用Fragment
 * “商品”、“自营”、“集采”、“促销”、“询价”、“供应商”
 */
public class CommodityMaterialFragment extends BaseHeightViewPagerFragment {
    @Inject
    CommodityMaterialModel viewModel;
    private FragmentCommodityMaterialBinding binding;
    private int mItemType;
    //自营与促销的适配器
    private MaterialHomeAdapter materialHomeAdapter;
    //供应商的适配器
    private SupplierRecommendAdapter supplierRecommendAdapter;
    //询价的适配器
    private DemandHallAdapter demandHallAdapter;
    //集采的适配器
    private FactoryCentralizedListItemAdapter factoryCentralizedListItemAdapter;
    //商品的适配器
    private MaterialHomeAdapter1 materialHomeAdapter1;
    //拍卖的适配器
    private AuctionHallAdapter auctionhalladapter;
    //商砼的单独实体
    private MenuEntity menuEntity1;
    //工程类别选项弹窗
    private HomeGoodsSelectionTypePopWindow mPopWindow;
    //工程类别选项弹窗的菜单数据
    List<MenuEntity> dictdata;
    public static final String MATERIAL = "material";//材料
    public static final String RECRUIT = "recruit";//招标
    public static final String RENT = "rent";//租赁
    public static final String TEAM = "team";//团队
    public static final String LOGISTICS = "logistics";//物流
    public static final String COLLEGE = "college";//知识分享
    public static final String GROUPBUY = "groupbuy";//集采
    private String enquiryid = "0";
    private String userid = "";
    private String sortid = "2";
    private String tabName = "全部";
    private String searchName = "";
    private String auctionHallNo = "";

    public static CommodityMaterialFragment newInstance(int position, BannerEntity bannerEntity, boolean isRefresh) {
        CommodityMaterialFragment fragment = new CommodityMaterialFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM, bannerEntity);
        args.putInt(ARG_PARAM_POS, position);
        args.putBoolean(ARG_isRefresh, isRefresh);
        fragment.setArguments(args);
        return fragment;
    }

    private int getItemType() {
        int mItemType = -1;
        BannerEntity bannerEntity = (BannerEntity) getArguments().getSerializable(ARG_PARAM);
        switch (bannerEntity.getName()) {
            case "商品":
                mItemType = 0;
                break;
            case "供应商":
                mItemType = 1;
                break;
            case "询价":
                mItemType = 2;
                break;
            case "促销":
                mItemType = 3;
                break;
            case "自营":
                mItemType = 4;
                break;
            case "集采":
                mItemType = 5;
                break;
            case "拍卖":
                mItemType = 6;
                break;
        }
        return mItemType;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() == null) {
            return;
        }
        mItemType = getItemType();
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_commodity_material, container, false);
        return binding.getRoot();
    }
    public void IsRefresh(boolean isRefresh) {
        setIsRefresh(isRefresh);
        loadData(false);
    }
    @Nullable
    @Override
    public View getView() {
        return super.getView();
    }

    @Override
    protected void initView() {
        super.initView();
        if (getArguments() == null) {
            return;
        }
        mItemType = getItemType();
        if (mItemType == -1) {
            return;
        }
        binding.tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        binding.recycler.setNestedScrollingEnabled(false);
        binding.recycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = getResources().getDimensionPixelSize(R.dimen.dp1);
            }
        });
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        switch (mItemType) {
            case 4://自营
                materialHomeAdapter = new MaterialHomeAdapter(getActivity(), null);
                binding.recycler.setLayoutManager(gridLayoutManager);
                binding.recycler.setAdapter(materialHomeAdapter);
                binding.tvMore.setBackground(getResources().getDrawable(R.color.transparent));
                binding.recycler.setPadding(0,0, (int) getActivity().getResources().getDimension(R.dimen.dp10),0);
                materialHomeAdapter.setOnItemClick(new AdapterOnItemClick<SearchMaterialEntity3>() {
                    @Override
                    public void onItemClick(SearchMaterialEntity3 searchMaterialEntity3, int position) {
                        if (!ClickUtils.isDoubleClick()) {
                            if (menuEntity1.getName().equals("商砼")) {
                                MaterialFilterJson filterJson = new MaterialFilterJson();
                                if (TextUtils.isEmpty(viewModel.materialFilterJson2.get().getStrengthId())) {
                                    filterJson.setStrengthId(searchMaterialEntity3.getStrengthId());
                                } else {
                                    filterJson.setStrengthId(viewModel.materialFilterJson2.get().getStrengthId());
                                }
                                filterJson.setGradationId(viewModel.materialFilterJson2.get().getGradationId());
                                filterJson.setServiceId(viewModel.materialFilterJson2.get().getServiceId());
                                ConcreteDetailActivity2.start(getActivity(), searchMaterialEntity3.getId(), filterJson);
                                return;
                            } else {
                                ShopGoodsDetailActivity.start(getActivity(), searchMaterialEntity3.getId(), "", searchMaterialEntity3.getSkuid());
                            }
                        }
                    }
                });
                binding.recycler.setAdapter(materialHomeAdapter);
                binding.llTabLayout.setVisibility(View.VISIBLE);
                break;
            case 1://供应商
                //判断适配器是否创建，未创建时创建适配器
                supplierRecommendAdapter  = new SupplierRecommendAdapter(getActivity(), null);
                //设置嵌套滑动为禁止状态，防止滑动冲突
                binding.recycler.setNestedScrollingEnabled(false);
                binding.recycler.setLayoutManager(new LinearLayoutManager(getContext()));
                binding.recycler.setPadding(0,0,0,0);
                //列表添加装饰者，距离底部1dp并设置颜色
                binding.recycler.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));
                //列表的子条目的点击事件
                supplierRecommendAdapter.setOnItemClick(new AdapterOnItemClick<SupplierRecommendEntity>() {
                    @Override
                    public void onItemClick(SupplierRecommendEntity supplierRecommendEntity, int position) {
                        //防止重复点击
                        if (!ClickUtils.isDoubleClick()) {
                            if (TextUtils.isEmpty(supplierRecommendEntity.getCompanyId())) {
                                ToastUtil.show(getActivity(), "企业店铺id不能为空");
                                return;
                            }
                            ShopInfoForCompanyTradesActivity.startAct(getActivity(), supplierRecommendEntity.getCompanyId(), "", 0, 0);
                        }
                    }
                });
                binding.recycler.setAdapter(supplierRecommendAdapter);
                binding.llTabLayout.setVisibility(View.GONE);
                break;
            case 2://询价
                if (demandHallAdapter == null) {
                    demandHallAdapter = new DemandHallAdapter(getActivity(), null);
                }
                binding.recycler.setLayoutManager(new LinearLayoutManager(getContext()));
                binding.recycler.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));
                demandHallAdapter.setOnItemClick(new AdapterOnItemClick<DemandHallListEntity>() {
                    @Override
                    public void onItemClick(DemandHallListEntity demandHallListEntity, int position) {
                        //防止重复点击
                        if (!ClickUtils.isDoubleClick()) {
                            viewModel.showUrl(demandHallListEntity.getEnquiryNo());
                        }
                    }
                });
                binding.recycler.setAdapter(demandHallAdapter);
                binding.llTabLayout.setVisibility(View.VISIBLE);
                break;
            case 3://促销
                materialHomeAdapter = new MaterialHomeAdapter(getActivity(), null);
                binding.recycler.setLayoutManager(gridLayoutManager);
                binding.recycler.setPadding(0,0, (int) getActivity().getResources().getDimension(R.dimen.dp10),0);
                binding.tvMore.setBackground(getResources().getDrawable(R.color.transparent));
                materialHomeAdapter.setOnItemClick(new AdapterOnItemClick<SearchMaterialEntity3>() {
                    @Override
                    public void onItemClick(SearchMaterialEntity3 searchMaterialEntity3, int position) {
                        //防止重复点击
                        if (!ClickUtils.isDoubleClick()) {
                            ShopGoodsDetailActivity.start(getActivity(), searchMaterialEntity3.getId(), "", searchMaterialEntity3.getSkuid());
                        }
                    }
                });
                binding.recycler.setAdapter(materialHomeAdapter);
                binding.llTabLayout.setVisibility(View.VISIBLE);
                break;
            case 0://商品
                materialHomeAdapter1 = new MaterialHomeAdapter1(getActivity(), null);
                binding.recycler.setLayoutManager(gridLayoutManager);
                binding.recycler.setPadding(0,0, (int) getActivity().getResources().getDimension(R.dimen.dp10),0);
                materialHomeAdapter1.setOnItemClick(new AdapterOnItemClick<SearchMaterialEntity3>() {
                    @Override
                    public void onItemClick(SearchMaterialEntity3 searchMaterialEntity3, int position) {
                        if (dictdata.get(binding.tabLayout.getSelectedTabPosition()).getId().equals("7")) {
                            ConcreteDetailActivity2.start(getActivity(), searchMaterialEntity3.getId());
                        } else {
                            ShopGoodsDetailActivity.start(getContext(), searchMaterialEntity3.getId(), "", searchMaterialEntity3.getSkuid());
                        }
                    }
                });
                binding.recycler.setAdapter(materialHomeAdapter1);
                binding.llTabLayout.setVisibility(View.VISIBLE);
                break;
            case 5://集采
                if (factoryCentralizedListItemAdapter == null) {
                    factoryCentralizedListItemAdapter = new FactoryCentralizedListItemAdapter(getActivity(), null);
                }
                binding.recycler.setLayoutManager(new LinearLayoutManager(getContext()));
                binding.recycler.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));
                factoryCentralizedListItemAdapter.setItemCallBack(new FactoryCentralizedListItemAdapter.ItemClickCallBack() {
                    @Override
                    public void onItemClick(FactoryCentralizedItemEntity entity) {
                        if (!ClickUtils.isDoubleClick()) {
                            viewModel.getH5Url(entity.getNo());
                        }
                    }
                });
                binding.recycler.setAdapter(factoryCentralizedListItemAdapter);
                binding.llTabLayout.setVisibility(View.VISIBLE);
                break;
            case 6: //拍卖大厅
                if (auctionhalladapter == null) {
                    auctionhalladapter = new AuctionHallAdapter(getActivity(), R.layout.ayction_hall_items1, null);
                }
                binding.recycler.setLayoutManager(new GridLayoutManager(getActivity(), 2));
                binding.recycler.setAdapter(auctionhalladapter);
                auctionhalladapter.setOnItemClick(new AdapterOnItemClick<AuctionListEntity>() {
                    @Override
                    public void onItemClick(AuctionListEntity auctionListEntity, int position) {
                        viewModel.getWebView(auctionListEntity.getNo());
                    }
                });
                binding.llTabLayout.setVisibility(View.VISIBLE);
                break;

        }
        binding.tvMore.setOnClickListener(v -> loadData(true));
        binding.ivPopup.setOnClickListener(v -> showPopup());
        binding.tvGoModel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 1));
            }
        });
        binding.tvGoModel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 1));
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        switch (mItemType) {
            case 0://商品
            case 2://询价
            case 3://促销
            case 4://自营
            case 5://集采
                //获取商品列表
                viewModel.recomandCate(MATERIAL);
                break;
            case 1://供货商
                viewModel.getSupplierMapModel(false,getIsRefresh());//请求列表数据接口
                break;
            case 6://拍卖大厅
                viewModel.getAuctionHallTabList();
                break;
        }
    }

    @Override
    public void onVisible() {
        super.onVisible();
            loadData(false);
    }

    private void loadData(boolean isLoadMore) {
        switch (mItemType) {
            case 0://商品
            case 4://自营
                if (menuEntity1 != null) {
                    if (menuEntity1.getName().equals("商砼")) {
                        viewModel.getSTData(isLoadMore, mItemType);
                    } else {
                        viewModel.getMaterialModel(menuEntity1.getName(), menuEntity1.getId(), isLoadMore, mItemType, getIsRefresh());
                    }
                }
                break;
            case 1://供应商
                viewModel.getSupplierMapModel(isLoadMore, getIsRefresh());//请求列表数据接口
                break;
            case 2://询价
                viewModel.getDemandHallList(userid, sortid, enquiryid, tabName, searchName, isLoadMore, getIsRefresh());
                break;
            case 3://促销
                if (menuEntity1 != null) {
                    viewModel.getMaterialModel2(menuEntity1.getId(), isLoadMore, mItemType, getIsRefresh());
                }
                break;
            case 5://集采
                if (menuEntity1 != null) {
                    viewModel.getFactoryCentralizedList(isLoadMore, getIsRefresh(), menuEntity1.getId());
                }
                break;
            case 6://招标大厅
                if (menuEntity1 != null) {
                    auctionHallNo = menuEntity1.getId();
                }
                viewModel.AuctionHallList(auctionHallNo, isLoadMore);
                break;
        }
    }

    //展示工程类别数据
    public <T> void showTypeData(List<T> list) {
        dictdata = (List<MenuEntity>) list;
        if (dictdata == null || dictdata.size() == 0) {
            binding.emptyView.setVisibility(View.VISIBLE);
            binding.llTabLayout.setVisibility(View.INVISIBLE);
            return;
        }
        binding.llTabLayout.setVisibility(View.VISIBLE);
        //循环
        for (int i = 0; i < dictdata.size(); i++) {
            //创建tab的item
            binding.tabLayout.addTab(binding.tabLayout.newTab().setText(dictdata.get(i).getName()));
        }
        menuEntity1 = dictdata.get(0);
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                menuEntity1 = dictdata.get(tab.getPosition());
                tabName = menuEntity1.getName();
                mPopWindow = new HomeGoodsSelectionTypePopWindow(getActivity());
                //弹窗设置数据
                mPopWindow.setData(dictdata);
                mPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
                    @Override
                    public void result(Object key1, Object key2, Object key3) {
                        binding.ivPopup.setImageResource(R.mipmap.btn_expand2);
                        Objects.requireNonNull(binding.tabLayout.getTabAt(((int) key2))).select();

                    }
                });
                mPopWindow.setDefItem(tab.getPosition());
                loadData(false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        loadData(false);
    }

    public <T> void showList(List<T> list, boolean isLoadMore) {
        switch (mItemType) {
            case 0://商品
                updateData(materialHomeAdapter1, (List<SearchMaterialEntity3>) list, isLoadMore);
                //DialogHelperNew.dismissProgressDialog();
                break;
            case 3://促销
            case 4://自营
                updateData(materialHomeAdapter, (List<SearchMaterialEntity3>) list, isLoadMore);
                break;
            case 1://供应商
                updateData(supplierRecommendAdapter, (List<SupplierRecommendEntity>) list, isLoadMore);
                break;
            case 2://询价
                updateData(demandHallAdapter, (List<DemandHallListEntity>) list, isLoadMore);
                break;
            case 5://集采
                updateData(factoryCentralizedListItemAdapter, (List<FactoryCentralizedItemEntity>) list, isLoadMore);
                break;
            case 6://拍卖
                updateData(auctionhalladapter, (List<AuctionListEntity>) list, isLoadMore);
                break;

        }

    }

    //加载或更新数据
    public <T> void updateData(BaseRecycleAdapter<T> adapter, List<T> list, boolean isLoadMore) {
        if (isLoadMore) {
            if (list != null && list.size() > 0) {
                adapter.addDatas(list);
            } else {
                binding.lineMore.setVisibility(View.VISIBLE);
                binding.tvMore.setVisibility(View.GONE);
            }
        } else {
            if (list != null && list.size() > 0) {
                binding.lineMore.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
            } else {
                binding.lineMore.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
            adapter.setDatas(list);
        }
    }

    //从适配器中获取前三条数据
    public <T> void loadCacheData(BaseRecycleAdapter<T> adapter) {
        List<T> data = adapter.getDatas();
        if (mItemType == 0 || mItemType == 3) {
            if (data != null && data.size() >= 6) {
                List<T> tempList = new ArrayList<>();
                tempList.add(data.get(0));
                tempList.add(data.get(1));
                tempList.add(data.get(2));
                tempList.add(data.get(3));
                tempList.add(data.get(4));
                tempList.add(data.get(5));
                adapter.setDatas(tempList);
            }
        } else {
            if (data != null && data.size() >= 3) {
                List<T> tempList = new ArrayList<>();
                tempList.add(data.get(0));
                tempList.add(data.get(1));
                tempList.add(data.get(2));
                adapter.setDatas(tempList);
            }
        }
    }

    //展开弹窗
    private void showPopup() {
        if (mPopWindow == null) {
            mPopWindow = new HomeGoodsSelectionTypePopWindow(getActivity());
            mPopWindow.setDefItem(0);
            mPopWindow.setData(dictdata);
            mPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
                @Override
                public void result(Object key1, Object key2, Object key3) {
                    binding.ivPopup.setImageResource(R.mipmap.btn_expand2);
                    Objects.requireNonNull(binding.tabLayout.getTabAt(((int) key2))).select();
                }
            });
            mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    binding.ivPopup.setImageResource(R.mipmap.btn_expand2);
                }
            });
        }
        binding.ivPopup.setImageResource(R.mipmap.btn_expand3);
        mPopWindow.showPopwindow(binding.ivPopup, true);
    }

    public void showUrl(String url) {
        WebViewX5HostActivity.start(getActivity(), url);
    }

}
